defmodule ShortEner.Plug.VerifyRequest do

  require Logger
  alias Logger, as: LOG

  defmodule IncompleteRequestError do
    @moduledoc """
    Error raised when a required field is missing.
    """

    defexception message: ""
  end

  def init(options), do: options

  def call(%Plug.Conn{request_path: path} = conn, opts) do
    if path in opts[:paths], do: verify_request!(conn.params, opts[:fields])
    conn
  end

  defp verify_request!(params, fields) do
    # %{"content" => "thing1", "mimetype" => "thing2"}
    #LOG.info("params: #{Map.keys(params)}")
    #Enum.each(params, fn(x) -> IO.puts x end)
    #LOG.info("values: #{Map.values(params)}")
    #LOG.info("keys: #{Map.keys(params)}")
    Enum.each(params, fn ({key, value}) -> 
      LOG.info("k:v: #{key}:#{value}")
      #IO.puts key
      #IO.puts params[key] 
    end)

    verified =
      params
      |> Map.keys()
      |> contains_fields?(fields)

    unless verified, do: raise(IncompleteRequestError)
  end

  defp contains_fields?(keys, fields) do
    #LOG.info("keys: #{keys}")
    #LOG.info("fields: #{fields}")
    Enum.all?(fields, &(&1 in keys))
  end
end

